import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { PwdInfo } from '@/api/pwd/type'

// 定义 Store
export const usePwdListStore = defineStore(
  'pwdList',
  () => {
    const searchValue = ref<string>()
    const pwdList = ref<PwdInfo[]>([])
    const version = ref<number>(0)

    const setList = (list: PwdInfo[]) => {
      pwdList.value = list
    }

    const clear = () => {
      pwdList.value = []
    }
    const clearSearch = () => {
      searchValue.value = ''
    }
    const setVersion = (value: number) => {
      version.value = value
    }

    const getPwdList = (): PwdInfo[] => {
      let searchString = searchValue.value
      return pwdList.value.filter((item) => {
        if (!searchString) return true
        // 全部变为大写再进行包含比较
        searchString = searchString.toUpperCase()
        return item.title?.toUpperCase().includes(searchString) || item.username?.toUpperCase().includes(searchString)
      })
    }
    const getVersion = () => {
      return version.value
    }

    // 记得 return
    return {
      searchValue,
      pwdList,
      version,
      setList,
      clear,
      getPwdList,
      setVersion,
      getVersion,
      clearSearch,
    }
  },
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value) // [!code warning]
        },
        getItem(key) {
          return uni.getStorageSync(key) // [!code warning]
        },
      },
    },
  },
)
